package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.StoreReceiptMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仓库库单模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/store-receipt")
public class StoreReceiptController {
    @Resource
    IStoreReceiptService storeReceiptService;
    @Resource
    StoreReceiptMapper storeReceiptMapper;
    @Resource
    IAdminService adminService;
    @Resource
    IStoreService storeService;
    @Resource
    IProductService productService;
    @Resource
    IStoreCommodityService storeCommodityService;
    @Resource
    ISupplierService supplierService;
    @Resource
    ICustomerService customerService;

    /**
     * 添加仓库库单
     * @param storeReceipt
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody StoreReceipt storeReceipt) {
        //更新库存信息
        if (storeReceipt.getType().equals("inbound")){
            // 获取产品id
            Integer productId = storeReceipt.getProductId();
            Integer storeId = storeReceipt.getStoreId();
            // 根据产品id查询是否存在货物
            QueryWrapper<StoreCommodity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_id", productId);
            queryWrapper.eq("store_id", storeId);
            StoreCommodity storeCommodity = storeCommodityService.getOne(queryWrapper);
            // 如果存在货物
            if(storeCommodity != null) {
                storeCommodity.setQuantity(storeCommodity.getQuantity()+storeReceipt.getQuantity());
                storeCommodityService.saveOrUpdate(storeCommodity);
            }
            else {
                StoreCommodity storeCommodity1 = new StoreCommodity();
                storeCommodity1.setProductId(productId);
                storeCommodity1.setStoreId(storeId);
                storeCommodity1.setStatus("正常");
                storeCommodity1.setQuantity(storeReceipt.getQuantity());
                Integer miniumQuantity = (int)Math.ceil(storeCommodity1.getQuantity() * 0.8);
                storeCommodity1.setMinimumQuantity(miniumQuantity);
                storeCommodityService.save(storeCommodity1);
            }
        }
        else {
            StoreCommodity storeCommodity = storeCommodityService.getById(storeReceipt.getStoreCommodityId());
            int quantity = storeCommodity.getQuantity()-storeReceipt.getQuantity();
            if (quantity>=0) {
                storeCommodity.setQuantity(storeCommodity.getQuantity() - storeReceipt.getQuantity());
            }else {
                return Result.error("库存不足，无法出库！");
            }
            if (storeCommodity.getQuantity()<storeCommodity.getMinimumQuantity()){
                storeCommodity.setStatus("异常");
            }
            System.out.println(storeCommodity);
            storeCommodityService.saveOrUpdate(storeCommodity);
        }
        Integer productId = storeReceipt.getProductId();
        Integer storeId = storeReceipt.getStoreId();
        // 根据产品id查询是否存在货物
        QueryWrapper<StoreCommodity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("store_id", storeId);
        StoreCommodity storeCommodity2 = storeCommodityService.getOne(queryWrapper);
        storeReceipt.setStoreCommodityId(storeCommodity2.getId());
        boolean res = storeReceiptService.save(storeReceipt);
        if(res) {
            return Result.success("添加仓库库单成功！");
        }
        return Result.error("添加仓库库单失败！");
    }

    /**
     * 删除仓库库单
     * @param storeReceipt
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody StoreReceipt storeReceipt) {
        boolean res = storeReceiptService.removeById(storeReceipt);
        if(res) {
            return Result.success("删除仓库库单成功！");
        }
        return Result.error("删除仓库库单失败！");
    }

    /**
     * 查询所有仓库库单
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<StoreReceipt> storeReceiptList = storeReceiptService.list();
        if(storeReceiptList != null) {
            return Result.success("查询所有仓库库单成功！", storeReceiptList);
        }
        return Result.error("查询所有仓库库单失败！");
    }

    /**
     * 删除一系列仓库单据
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> storeReceiptIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = storeReceiptService.removeByIds(storeReceiptIds);
        if(res) {
            return Result.success("删除仓库订单成功");
        }
        return Result.error("删除仓库订单失败！");
    }

    /**
     * 修改仓库单据
     *
     * @param storeReceipt
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody StoreReceipt storeReceipt) {
        int qb = storeReceipt.getQuantityBefore();
        //更新库存信息
        if (storeReceipt.getType().equals("inbound")) {
            StoreCommodity storeCommodity = storeCommodityService.getById(storeReceipt.getStoreCommodityId());
            storeCommodity.setQuantity(storeCommodity.getQuantity() + (storeReceipt.getQuantity()-qb));
            if (storeCommodity.getQuantity()>=storeCommodity.getMinimumQuantity()){
                storeCommodity.setStatus("正常");
            }
            else {
                storeCommodity.setStatus("异常");
            }
            storeCommodityService.saveOrUpdate(storeCommodity);
        } else {
            StoreCommodity storeCommodity = storeCommodityService.getById(storeReceipt.getStoreCommodityId());
            int quantity = storeCommodity.getQuantity() - (storeReceipt.getQuantity()-qb);
            if (quantity >= 0) {
                storeCommodity.setQuantity(quantity);
            } else {
                return Result.error("库存不足，无法出库！");
            }
            if (quantity>=storeCommodity.getMinimumQuantity()){
                storeCommodity.setStatus("正常");
            }
            else {
                storeCommodity.setStatus("异常");
            }
            storeCommodityService.saveOrUpdate(storeCommodity);
        }
        boolean res = storeReceiptService.saveOrUpdate(storeReceipt);
        if (res) {
            return Result.success("修改仓库单据成功！");
        }
        return Result.error("修改仓库单据失败！");
    }

    /**
     * 查询所有库单负责人
     * @return
     */
    @GetMapping("/findAdminsInboundDocument")
    public Result findAdminsInProductAttribute() {
        List<Admin> adminList = storeReceiptService.findAdminsInboundDocument();
        if(adminList == null) {
            return Result.error("获取管理员信息失败！");
        }
        return Result.success(adminList);
    }

    /**
     * 分页查询所有的仓库库单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam(defaultValue = "-1") String storeId,
                           @RequestParam(defaultValue = "-1") String objectId,
                           @RequestParam(defaultValue = "") String productName,
                           @RequestParam(defaultValue = "") String type,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<StoreReceipt> storeReceiptPage = new Page<>(pageNum, pageSize);
        List<StoreReceipt> storeReceiptList = storeReceiptMapper.getStoreReceiptByPage(storeReceiptPage, adminId, storeId, objectId, productName, type);
        for(StoreReceipt storeReceipt : storeReceiptList) {
            if(storeReceipt.getStoreId() != null) {
                Store store = storeService.getById(storeReceipt.getStoreId());
                storeReceipt.setStoreName(store.getName());
            }
            if(storeReceipt.getAdminId() != null) {
                Admin admin = adminService.getById(storeReceipt.getAdminId());
                storeReceipt.setAdminName(admin.getName());
            }
            if(storeReceipt.getObjectId() != null) {
                if(type.equals("inbound")) {
                    Supplier supplier = supplierService.getById(storeReceipt.getObjectId());
                    storeReceipt.setObjectName(supplier.getName());
                }
                else {
                    Customer customer = customerService.getById(storeReceipt.getObjectId());
                    if(customer != null) {
                        storeReceipt.setObjectName(customer.getName());
                    }
                }
            }
            if(storeReceipt.getStoreCommodityId() != null) {
                StoreCommodity storeCommodity = storeCommodityService.getById(storeReceipt.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                storeReceipt.setStoreCommodityName(product.getName());
            }
        }
        Page<StoreReceipt> newStoreReceiptPage = new Page<>(pageNum, pageSize);
        newStoreReceiptPage.setRecords(storeReceiptList);
        newStoreReceiptPage.setTotal(storeReceiptPage.getTotal());
        return Result.success("成功查询所有库单！", newStoreReceiptPage);
    }

    /**
     * 导出仓库库单
     *
     * @param response
     * @return
     */
    @GetMapping("exportStoreReceiptList")
    public Result exportStoreReceiptList(@RequestParam(defaultValue = "-1") String adminId,
                                         @RequestParam(defaultValue = "-1") String storeId,
                                         @RequestParam(defaultValue = "-1") String objectId,
                                         @RequestParam(defaultValue = "") String productName,
                                         @RequestParam(defaultValue = "") String type,
                                         HttpServletResponse response) {
        QueryWrapper<StoreReceipt> queryWrapper = new QueryWrapper<>();
        List<StoreReceipt> storeReceiptList = storeReceiptService.list(queryWrapper);
        for (StoreReceipt storeReceipt : storeReceiptList) {
            if (storeReceipt.getStoreId() != null) {
                Store store = storeService.getById(storeReceipt.getStoreId());
                storeReceipt.setStoreName(store.getName());
            }
            if(storeReceipt.getAdminId() != null) {
                Admin admin = adminService.getById(storeReceipt.getAdminId());
                storeReceipt.setAdminName(admin.getName());
            }
            if(storeReceipt.getObjectId() != null) {
                if(type.equals("inbound")) {
                    Supplier supplier = supplierService.getById(storeReceipt.getObjectId());
                    storeReceipt.setObjectName(supplier.getName());
                }
                else {
                    Customer customer = customerService.getById(storeReceipt.getObjectId());
                    storeReceipt.setObjectName(customer.getName());
                }
            }
            if(storeReceipt.getStoreCommodityId() != null) {
                StoreCommodity storeCommodity = storeCommodityService.getById(storeReceipt.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                storeReceipt.setStoreCommodityName(product.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        if(type.equals("inbound"))
        {
            cell = row.createCell((short) 1);
            cell.setCellValue("入库仓库");
            cell.setCellStyle(style);
            cell = row.createCell((short) 2);
            cell.setCellValue("入库货品");
            cell.setCellStyle(style);
            cell = row.createCell((short) 3);
            cell.setCellValue("供应商");
            cell.setCellStyle(style);
        }
        else {
            cell = row.createCell((short) 1);
            cell.setCellValue("出库仓库");
            cell.setCellStyle(style);
            cell = row.createCell((short) 2);
            cell.setCellValue("出库货品");
            cell.setCellStyle(style);
            cell = row.createCell((short) 3);
            cell.setCellValue("客户");
            cell.setCellStyle(style);
        }
        cell = row.createCell((short)4);
        cell.setCellValue("价格");
        cell.setCellStyle(style);
        cell = row.createCell((short) 5);
        cell.setCellValue("数量");
        cell.setCellStyle(style);
        if(type.equals("inbound")) {
            cell = row.createCell((short) 6);
            cell.setCellValue("采购负责人");
            cell.setCellStyle(style);
        }
        else {
            cell = row.createCell((short) 6);
            cell.setCellValue("出库负责人");
            cell.setCellStyle(style);
        }
        cell = row.createCell((short) 7);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int r=1;
        for (int i = 0; i < storeReceiptList.size(); i++) {
            row = sheet.createRow(r);
            StoreReceipt storeReceipt = storeReceiptList.get(i);
            if (storeReceipt.getType().equals(type)) {
                row.createCell((short) 0).setCellValue(storeReceipt.getId());
                row.createCell((short) 1).setCellValue(storeReceipt.getStoreName());
                row.createCell((short) 2).setCellValue(storeReceipt.getStoreCommodityName());
                row.createCell((short) 3).setCellValue(storeReceipt.getObjectName());
                row.createCell((short) 4).setCellValue(storeReceipt.getPrice());
                row.createCell((short) 5).setCellValue(storeReceipt.getQuantity());
                row.createCell((short) 6).setCellValue(storeReceipt.getAdminName());
                try {
                    Date createTime = inputDateFormat.parse(storeReceipt.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                    row.createCell((short) 7).setCellValue(outputDateFormat.format(createTime));
                } catch (ParseException e) {
                    row.createCell((short) 7).setCellValue(storeReceipt.getCreateTime().toString());
                }
                ++r;
            }
        }
        String fileName = "exportStoreReceiptList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductBrandList");
    }
}
